package com.mc.code.web;

import com.mc.code.entity.CodeItems;
import com.mc.code.entity.CodeUsers;
import com.mc.code.entity.ItemStage;
import com.mc.code.entity.Stage;
import com.mc.code.service.ItemsService;
import com.mc.code.service.StageService;
import com.mc.code.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;


@Controller
@RequestMapping("/mc/stage")
public class StageController {
    private static final long serialVersionUID = 1L;
    private static final int PAGE_COUNT = 5;//每页显示记录数
    @Autowired
    private UsersService usersService;

    @Autowired
    private ItemsService itemsService;
    @Autowired
    private StageService stageService;


    //    查看我参与的项目
    @RequestMapping("participatingProjects")
    public String participatingProjects(Model model,HttpSession httpSession, HttpServletRequest request, String userNo,String page) {
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        //默认当前页
        int currentPage = 1;
        if(page != null) {
            currentPage = Integer.valueOf(page);
        }
        List<CodeItems> codeItems = stageService.partakeItems(userNo,currentPage,PAGE_COUNT);
        int totalPage = stageService.getMyPartakeTotalPage(PAGE_COUNT,userNo);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage", currentPage);
        model.addAttribute("codeItems", codeItems);
        model.addAttribute("stageCondition", httpSession.getAttribute("stageCondition"));
        return "participatingProjects";
    }


    //   阶段划分
    @RequestMapping("stageDivision")
    public String stageDivision(Model model, HttpServletRequest request, String userNo, Integer itemNo) {
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        return "stageDivision";
    }

    /**
     *
     */
//    阶段划分提交
    @RequestMapping(value = "/saveStage", method = {RequestMethod.POST})
    public String save(Model model, HttpServletRequest request, HttpSession httpSession) {
        int i = 0;
        List<Stage> stages = new ArrayList<>();
        int stageNum;//阶段数
        String stageName;//阶段名称
        String stageDate;//阶段交付日期
        double stageMoney;//阶段金额
        String stageExplain;//交付说明
        while (request.getParameter("list[" + i + "].stageNum") != null) {
            stageNum = Integer.parseInt(request.getParameter("list[" + i + "].stageNum").substring(1));
            stageName = request.getParameter("list[" + i + "].stageName");
            stageDate = request.getParameter("list[" + i + "].stageDate");
            String money = request.getParameter("list[" + i + "].stageMoney");
            if (money != null)
                stageMoney = Double.parseDouble(money);
            else stageMoney = 0;
            stageExplain = request.getParameter("list[" + i + "].stageExplain");
            stages.add(new Stage(stageNum, stageName, stageDate, stageMoney, stageExplain));
            i++;
        }
        String userNo = request.getParameter("userNo");
        int itemNo = Integer.parseInt(request.getParameter("itemNo"));
        for (int j = 0; j < i; j++) {
            stageService.divideInsertStage(i, userNo, itemNo, stages.get(j).getStageNum(), stages.get(j).getStageName(), stages.get(j).getStageDate(), stages.get(j).getStageMoney(), stages.get(j).getStageExplain());
        }
        stageService.updateStageCondition(itemNo, userNo);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        List<CodeItems> codeItems = stageService.partakeItems(userNo, 1, PAGE_COUNT);
        model.addAttribute("codeItems", codeItems);
        int currentPage = 1;
        int totalPage = stageService.getMyPartakeTotalPage(PAGE_COUNT,userNo);
        model.addAttribute("totalPage", totalPage);
        model.addAttribute("currentPage",currentPage);
        int stageCondition=stageService.stageConditiondivision(itemNo,userNo);
        httpSession.setAttribute("stageCondition",stageCondition);
        return "participatingProjects";
    }


    @RequestMapping("stageList")
    public String stageList(String userNo, String partakeNo, Integer itemNo, Model model, Integer stageCondition, HttpServletRequest request) {
        if (stageCondition != null) {
            stageService.StageCondition(partakeNo, itemNo, stageCondition);
            if (stageCondition == 3) {
                stageService.stageDetailAgree(itemNo, partakeNo);
                int i = stageService.stageNum(itemNo, partakeNo);
                stageService.stageGeneral(itemNo, partakeNo, i);
            }
        }
        List<ItemStage> itemStages = stageService.itemStage(itemNo);
        model.addAttribute("itemStages", itemStages);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);
        return "stageList";
    }


    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    @RequestMapping("stageStartList")
    public String stageStartList(String userNo, Integer itemNo, Model model, HttpServletRequest request) {
        List<ItemStage> itemStages = stageService.itemStartStage(itemNo);
        model.addAttribute("itemStages", itemStages);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);
        return "stageStartList";
    }
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


    @RequestMapping("stageDetails")
    public String stageDetails(String userNo, Integer itemNo, Integer partakeNo, Model model, HttpServletRequest request) {
        List<Stage> stages = stageService.stageDetail(partakeNo,itemNo);
        model.addAttribute("stages", stages);
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        model.addAttribute("partakeNo", partakeNo);
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);
        return "stageDetail";
    }

    //    开始每个阶段的工作
    @RequestMapping("stageDo")
    public String stageDo(HttpServletRequest request, Model model, String userNo, Integer itemNo) {
        List<Stage> stages = stageService.stageDetailStart(userNo, itemNo);
        model.addAttribute("stages", stages);//所有的需求方同意的自己划分的阶段详情
        int num = stages.size();
        model.addAttribute("num", num);//总阶段数
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);//项目编号
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        int stageCurrent = stageService.stageCurrent(itemNo, userNo);
        model.addAttribute("stageCurrent", stageCurrent);
        int stageNow = stageService.stageNow(itemNo, userNo);
        model.addAttribute("stageNow", stageNow);
        return "stageDo";
    }

    //    查看每个阶段的工作
    @RequestMapping("stageStart")
    public String stageStart( Model model, String userNo, Integer itemNo, String partakeNo) {
        List<Stage> stages = stageService.stageDetailStart(partakeNo, itemNo);
        model.addAttribute("stages", stages);//所有的需求方同意的自己划分的阶段详情
        int num = stages.size();
        model.addAttribute("num", num);//总阶段数
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);//项目编号
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        int stageCurrent = stageService.stageCurrent(itemNo, partakeNo);
        model.addAttribute("stageCurrent", stageCurrent);
        int stageNow = stageService.stageNow(itemNo, partakeNo);
        model.addAttribute("stageNow", stageNow);
        String fileName = stageService.downLoadStageFile(itemNo, partakeNo, stageNow);
        model.addAttribute("fileName", fileName);
        model.addAttribute("partakeNo", partakeNo);
        return "stageStart";
    }

    //    查看每个阶段的工作
    @RequestMapping("stageFinish")
    public String stageFinish(HttpServletRequest request, Model model, String userNo, Integer itemNo, String partakeNo) {
        List<Stage> stages = stageService.stageDetailStart(partakeNo, itemNo);
        model.addAttribute("stages", stages);//所有的需求方同意的自己划分的阶段详情
        int num = stages.size();
        model.addAttribute("num", num);//总阶段数
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);//项目编号
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        int stageCurrent = stageService.stageCurrent(itemNo, partakeNo);
        model.addAttribute("stageCurrent", stageCurrent);
        int stageNow = stageService.stageNow(itemNo, partakeNo);
        model.addAttribute("stageNow", stageNow);
        String fileName = stageService.downLoadStageFile(itemNo, partakeNo, stageNow);
        model.addAttribute("fileName", fileName);
        model.addAttribute("partakeNo", partakeNo);
        return "stageFinish";
    }


    @RequestMapping("stageFile")
    public String stageFile(HttpServletRequest request, Model model, String partakeNo, Integer stageNum, Integer itemNo) throws IOException {
        stageNum = stageNum + 1;
        //提交阶段文件验收
        stageService.updateStageCurrent(partakeNo, stageNum, itemNo);
        //提交文件
//        文件上传
        //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        String filename = null;
        if (multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                String pa = "E:/inno/ideaIUWorkSpace/pic/";
                //一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                if (file != null) {
                    String path = file.getOriginalFilename();
                    //找到.的下标
                    int begin = path.indexOf(".");
                    //找到字符串末位下标，即字符串长度
                    int last = path.length();
                    String str = null;
                    if (begin != -1) {
                        str = path.substring(begin);
                    }
//                    图片格式有：BMP、JPG、JPEG、PNG、GIF。
                    if (str != null) {
                        String fileName = UUID.randomUUID() + path.substring(begin, last);
                        //上传
                        filename = fileName;
                        file.transferTo(new File(pa + fileName));
                    }
                }
            }
        }
        //    插入数据库
        stageService.uploadStageFile(filename, itemNo, partakeNo, stageNum);
        List<Stage> stages = stageService.stageDetailStart(partakeNo, itemNo);
        model.addAttribute("stages", stages);//所有的需求方同意的自己划分的阶段详情
        int num = stages.size();
        model.addAttribute("num", num);//总阶段数
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);//项目编号
        List<CodeUsers> codeUsers = usersService.codeUsers(partakeNo);
        model.addAttribute("codeUsers", codeUsers);
        int stageCurrent = stageService.stageCurrent(itemNo, partakeNo);
        model.addAttribute("stageCurrent", stageCurrent);
        int stageNow = stageService.stageNow(itemNo, partakeNo);
        model.addAttribute("stageNow", stageNow);
        return "stageDo";
    }


//   支付资金
  @ResponseBody
  @RequestMapping("stageFilePay")
  public String stageFilePay(HttpServletRequest request, Model model,
                               String partakeNo, Integer stageNum, @RequestParam("checkValue") Integer checkValue, Integer itemNo,
                               String userNo,  Integer pay, @RequestParam("password") String password
  ) {
      System.out.println(checkValue);
//        支付
      if (pay != null) {
          List<CodeUsers> u = usersService.codeUsers(userNo);
          String psd = usersService.payPsd(userNo);
          if (!(psd != null && !(psd.equals("")))) {
              return "nopsd";
          } else if (!psd.equals(password)) {
              return "支付密码错误，验收失败";
          } else {

              List<CodeItems> i = itemsService.itemsDetails(itemNo);
              if (u.get(0).getBanlance() < i.get(0).getMoney()) {
                  return "less";
              } else {
                  if (pay == 1) {
                      System.out.println("更新checkValue"+checkValue+itemNo+partakeNo);
                      stageService.ApplyStageCurrent(itemNo, partakeNo, checkValue);
                      List<CodeItems> item = itemsService.itemsDetails(itemNo);
                      List<CodeUsers> user = usersService.codeUsers(partakeNo);
                      List<CodeUsers> userN = usersService.codeUsers(userNo);
                      double money = user.get(0).getBanlance();
                      money += item.get(0).getMoney();
                      double moneyN = userN.get(0).getBanlance();
                      moneyN -= item.get(0).getMoney();
                      stageService.payPartakeNo(money, partakeNo);
                      stageService.payPartakeNo(moneyN, userNo);
                      stageService.finishItem(itemNo);
                      return "ok";
                  }
              }
          }
      }
      return "验收失败，请稍后再试";
  }



    //    验收通不通过
    @RequestMapping("stageFileAgree")
    public String stageFileAgree(HttpServletRequest request, Model model,
                                 String partakeNo, Integer stageNum, @RequestParam("checkValue") Integer checkValue, Integer itemNo,
                                 String userNo, Integer check, Integer pay  ) {
        if (check != null) {
            if (check == 1) {
                stageService.ApplyStageCurrent(itemNo, partakeNo, checkValue);
            } else if (check == 0) {
                stageService.ApplyStageNow(itemNo, partakeNo, checkValue);
            }
        }

        List<Stage> stages = stageService.stageDetailStart(partakeNo, itemNo);
        model.addAttribute("stages", stages);//所有的需求方同意的自己划分的阶段详情
        int num = stages.size();
        model.addAttribute("num", num);//总阶段数
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);//项目编号
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        int stageCurrent = stageService.stageCurrent(itemNo, partakeNo);
        model.addAttribute("stageCurrent", stageCurrent);
        int stageNow = stageService.stageNow(itemNo, partakeNo);
        model.addAttribute("stageNow", stageNow);
        model.addAttribute("partakeNo", partakeNo);
        return "stageStart";
    }

    //    返回上一阶段
    @RequestMapping("stageFileReturn")
    public String stageFileReturn( Model model,
                                 String partakeNo, Integer stageCurrent, Integer itemNo,Integer stageNow,
                                 String userNo ) {
        stageService.returnStage(itemNo, partakeNo, stageCurrent,stageNow);
        List<Stage> stages = stageService.stageDetailStart(partakeNo, itemNo);
        model.addAttribute("stages", stages);//所有的需求方同意的自己划分的阶段详情
        int num = stages.size();
        model.addAttribute("num", num);//总阶段数
        List<CodeItems> codeItems = itemsService.itemsDetails(itemNo);
        model.addAttribute("codeItems", codeItems);//项目编号
        List<CodeUsers> codeUsers = usersService.codeUsers(userNo);
        model.addAttribute("codeUsers", codeUsers);
        int stageCurrent2 = stageService.stageCurrent(itemNo, partakeNo);
        model.addAttribute("stageCurrent", stageCurrent2);
        int stageNow2 = stageService.stageNow(itemNo, partakeNo);
        model.addAttribute("stageNow", stageNow2);
        model.addAttribute("partakeNo", partakeNo);
        return "stageStart";
    }


}
